package org.light.framework.bean;


import java.util.ArrayList;
import java.util.HashMap;

import org.light.framework.orm.DbMapper;
import org.light.framework.orm.ManyToManyInfo;
import org.light.framework.util.StringUtil;

/**
 * 需要修改的项 如果需要保存的项为空或数量为空时，表示保存全部属性值 如果保存的项为空或数量为0，则读取不需要保存的项
 * 
 * @author de.cel
 *
 */
public class UpdateColumn {

	private ArrayList<String> includes = null;
	private ArrayList<String> excludes = null;

	/**
	 * 构造函数
	 * 默认更新多对多关联
	 * 
	 * @param type
	 */
	public UpdateColumn(Class<?> type) {
		HashMap<String, ManyToManyInfo> dic = DbMapper.getManyToMany(type);
		if (dic != null && !dic.isEmpty())
			isManyToManyUpdate = true;
		else
			isManyToManyUpdate = false;

		includes = new ArrayList<String>();
		excludes = new ArrayList<String>();
	}

	/**
	 * 是否更新多对多关联项
	 */
	public boolean isManyToManyUpdate;

	/**
	 * 添加需要查询的属性名（当需要保存的为项为0时，默认保存全部属性的值）
	 * 
	 * @param propertyName
	 */
	public void add(String propertyName) {
		if (!includes.contains(propertyName))
			includes.add(propertyName);
	}

	/**
	 * 删除不需要保存的属性名
	 * 
	 * @param propertyName
	 */
	public void delete(String propertyName) {
		if (!excludes.contains(propertyName))
			excludes.add(propertyName);
	}

	/**
	 * 结果中是否包含指定的属性名
	 * 
	 * @param propertyName
	 * @return
	 */
	public boolean include(String propertyName) {
		if (!includes.isEmpty() && !StringUtil.isNotNullOrEmpty(propertyName) && !including(propertyName)) {
			return false;
		}
		if (!StringUtil.isNotNullOrEmpty(propertyName) && excluding(propertyName)) {
			return false;
		}
		return true;
	}

	private boolean including(String propertyName) {
		for (String t : includes) {

			if (t.equals(propertyName) || (t.startsWith(propertyName) && t.contains(".")))
				return true;
		}
		return false;
	}

	private boolean excluding(String propertyName) {
		for (String t : includes) {
			if (t.equals(propertyName) || (propertyName.startsWith(t) && propertyName.contains(".")))
				return true;
		}
		return false;
	}
}
